package pers.litao.bit.commons.utils;


import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author litao
 * @date 2021/04/02
 */
public class SysUtil {
    public static LoginUserInfo getLoginUserInfo(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            //解析token
            Claims claims = JwtUtil.parseJWT(token);
            Long userId = claims.get("id", Long.class);
            String phone = claims.get("phone", String.class);
            Integer identity = claims.get("identity", Integer.class);
            return new LoginUserInfo(userId, phone, identity);

        } catch (Exception e) {
            return null;
        }
    }
    public static boolean isNumber(String num){
        try {
            Integer.valueOf(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static boolean isPhone(String phone){
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phone);
        return m.matches();
    }
    public static ClientInfo getClientInfo(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 得到请求的URL地址
        String requestUrl = request.getRequestURL().toString();
        // 得到请求的资源
        String requestUri = request.getRequestURI();
        // 得到来访者的IP地址
        String remoteAddr = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        int remotePort = request.getRemotePort();

        // 得到请求URL地址时使用的方法
        String method = request.getMethod();

        //获取WEB服务器的IP地址
        String localAddr = request.getLocalAddr();
        //获取WEB服务器的主机名
        String localName = request.getLocalName();
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setRequestUrl(requestUrl)
                .setRequestUri(requestUri)
                .setRemoteAddr(remoteAddr)
                .setRemotePort(remotePort)
                .setRemoteHost(remoteHost)
                .setLocalAddr(localAddr)
                .setLocalName(localName)
                .setMethod(method);
        return clientInfo;
    }
}
